<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>今天教什么</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .task-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .task-card {
            background: white;
            border-radius: 8px;
            padding: 1rem;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .task-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        .task-card.completed {
            border-left: 4px solid #4CAF50;
        }
        
        .task-card.failed {
            border-left: 4px solid #f44336;
            cursor: not-allowed;
        }
        
        .task-card.pending {
            border-left: 4px solid #ff9800;
            cursor: not-allowed;
        }
        
        .task-card h4 {
            margin: 0 0 0.5rem 0;
            color: #333;
        }
        
        .task-card p {
            margin: 0.25rem 0;
            color: #666;
            font-size: 0.9rem;
        }
        
        .task-card .status {
            font-weight: bold;
        }
        
        .task-card.completed .status {
            color: #4CAF50;
        }
        
        .task-card.failed .status {
            color: #f44336;
        }
        
        .task-card.pending .status {
            color: #ff9800;
        }
        
        .config-btn {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: none;
            border: none;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
        }
        
        .config-dialog {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            z-index: 1001;
            width: 500px;
            max-width: 90%;
        }
        
        .config-dialog h3 {
            margin-top: 0;
        }
        
        .config-dialog textarea {
            width: 100%;
            height: 200px;
            margin: 1rem 0;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        
        .pdf-container {
            display: flex;
            flex-direction: row;
            height: calc(100vh - 150px);
            margin-top: 20px;
        }
        
        .pdf-viewer {
            flex: 1;
            padding: 20px;
            background: white;
            margin-right: 10px;
            overflow: auto;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .text-viewer {
            flex: 1;
            padding: 20px;
            background: white;
            margin-left: 10px;
            overflow: auto;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            white-space: pre-wrap;
        }
        .loading-mask {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #4CAF50;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        header {
            background-color: #4CAF50;
            color: white;
            padding: 1rem;
            text-align: center;
        }
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 2rem;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        .search-container {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        #textInput {
            flex: 1;
            padding: 0.8rem 1.2rem;
            border: 1px solid #dfe1e5;
            border-radius: 24px;
            font-size: 1rem;
            outline: none;
            box-shadow: 0 1px 6px rgba(32,33,36,0.1);
        }
        
        #textInput:hover, #textInput:focus {
            box-shadow: 0 1px 6px rgba(32,33,36,0.2);
        }
        
        .file-upload-btn {
            background-color: #f8f9fa;
            color: #3c4043;
            border: 1px solid #dadce0;
            border-radius: 4px;
            padding: 0.8rem 1.2rem;
            cursor: pointer;
            font-size: 1rem;
        }
        
        .file-upload-btn:hover {
            background-color: #f1f3f4;
            border-color: #dadce0;
        }
        .upload-area:hover {
            border-color: #45a049;
            background-color: #f8fff8;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            cursor: pointer;
            font-size: 1rem;
        }
        button:hover {
            background-color: #45a049;
        }
        #result {
            margin-top: 2rem;
            padding: 1rem;
            background-color: white;
            border: 1px solid #ddd;
        }
        .result-container {
            margin-top: 2rem;
            padding: 1.5rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        .result-viewer {
            min-height: 200px;
            padding: 1rem;
            border: 1px solid #eee;
            border-radius: 4px;
        }
        .link-viewer {
            margin-top: 1rem;
            text-align: center;
        }
    </style>
</head>
<body>
    
    <header>
        <h1>今天教什么？</h1>
        <p>输入知识点或者题目文字或上传图片，生成交互式HTML页面</p>
        <button id="configBtn" class="config-btn"  style="right: 4rem;"><i class="fas fa-cog"></i></button>
        <button id="logoutBtn" class="config-btn"><i class="fas fa-sign-out-alt"></i></button>
    </header>

    <div class="config-dialog">
        <h3>提示词配置</h3>
        <textarea id="promptConfig" placeholder="请输入提示词配置..."></textarea>
        <div style="display: flex; justify-content: flex-end; gap: 1rem;">
            <button id="cancelConfigBtn">取消</button>
            <button id="saveConfigBtn">保存</button>
        </div>
    </div>

    <div class="loading-mask">
        <div class="loading-spinner"></div>
    </div>
    
    <div class="container">
        <div class="search-container">
            <input type="text" id="textInput" placeholder="输入搜索内容...">
            <label for="imageUpload" class="file-upload-btn">上传图片</label>
            <input type="file" id="imageUpload" accept="image/*" style="display: none;">
            <button id="searchBtn">生成HTML</button>
        </div>

        <!-- <div class="result-container">
            <div class="result-viewer" id="generatedHtml"></div>
            <div class="link-viewer" id="resultLink"></div>
        </div> -->
        <div class="task-cards" id="taskList"></div>
        <!-- <div class="container mt-4">
            <div class="row">
                <div class="col-md-12">
                    
                    <div class="task-cards" id="taskList"></div>
                </div>
            </div>
        </div> -->
    </div>

    <script>
        // 检查登录状态
        async function checkLogin() {
            // 首先检查localStorage中是否有token
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login';
                return false;
            }
            
            try {
                const response = await fetch('/api/check-login', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                if (!response.ok) {
                    window.location.href = '/login';
                    return false;
                }
                return true;
            } catch (error) {
                console.error('登录检查失败:', error);
                window.location.href = '/login';
                return false;
            }
        }

        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', async () => {
            await checkLogin();
            loadTasks();
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', async () => {
            try {
                await fetch('/api/logout', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                localStorage.removeItem('token');
                window.location.href = '/login';
            } catch (error) {
                console.error('退出登录失败:', error);
            }
        });

        document.getElementById('searchBtn').addEventListener('click', function() {
            const textInput = document.getElementById('textInput');
            const fileInput = document.getElementById('imageUpload');
            
            if (textInput.value === '' && fileInput.files.length === 0) {
                alert('请输入文字或上传图片');
                return;
            }
            
            // 显示加载蒙版
            document.querySelector('.loading-mask').style.display = 'flex';
            
            const formData = new FormData();
            if (textInput.value !== '') {
                formData.append('question', textInput.value);
            }
            if (fileInput.files.length > 0) {
                formData.append('file', fileInput.files[0]);
            }
            
            fetch('/api/gen-html', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                loadTasks();
            })
            .finally(() => {
                // 隐藏加载蒙版
                document.querySelector('.loading-mask').style.display = 'none';
            })
            .catch(error => {
                console.error('Error:', error);
                document.querySelector('.loading-mask').style.display = 'none';
                alert('Error processing');
            });
        });
    </script>
    <script>
        async function loadTasks() {
            const response = await fetch('/api/all-tasks', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });
            const tasks = await response.json();
            
            const taskList = document.getElementById('taskList');
            taskList.innerHTML = '';
            
            tasks.forEach(task => {
                const card = document.createElement('div');
                card.className = `task-card ${task.status.toLowerCase()}`;
                
                if(task.status === 'completed') {
                    card.onclick = () => window.open(task.result, '_blank');
                }
                
                card.innerHTML = `
                    <h4>任务 ${task.question || '无'}</h4>
                    <p class="status">状态: ${task.status}</p>
                    <p>创建时间: ${new Date(task.created_at * 1000).toLocaleString()}</p>
                `;
                taskList.appendChild(card);
            });
        }
        
        // 初始加载任务列表
        loadTasks();
        
        // 每5秒刷新一次任务列表
        setInterval(loadTasks, 5000);
        
        // 配置按钮交互
        const configBtn = document.getElementById('configBtn');
        const configDialog = document.querySelector('.config-dialog');
        const cancelConfigBtn = document.getElementById('cancelConfigBtn');
        const saveConfigBtn = document.getElementById('saveConfigBtn');
        
        configBtn.addEventListener('click', async () => {
            try {
                // 获取最新提示词
                const response = await fetch('/api/get-latest-prompt', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });
                const data = await response.json();
                document.getElementById('promptConfig').value = data.prompt_text || '';
                
                // 获取历史版本
                const historyResponse = await fetch('/api/get-prompts', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });
                const historyData = await historyResponse.json();
                
                // 添加历史版本选择器
                const historySelect = document.createElement('select');
                historySelect.id = 'historySelect';
                historySelect.className = 'form-select mb-3';
                historySelect.innerHTML = '<option value="">选择历史版本</option>' + 
                    historyData.map(item => 
                        `<option value="${item.prompt_text}" data-timestamp="${item.created_at}">
                            ${new Date(item.created_at * 1000).toLocaleString()}
                        </option>`
                    ).join('');
                
                historySelect.addEventListener('change', (e) => {
                    if (e.target.value) {
                        document.getElementById('promptConfig').value = e.target.value;
                    }
                });
                
                const dialogContent = document.querySelector('.config-dialog');
                if (!document.getElementById('historySelect')) {
                    dialogContent.insertBefore(historySelect, dialogContent.querySelector('textarea'));
                }
                
                configDialog.style.display = 'block';
            } catch (error) {
                console.error('获取提示词失败:', error);
                configDialog.style.display = 'block';
            }
        });
        
        cancelConfigBtn.addEventListener('click', () => {
            configDialog.style.display = 'none';
        });
        
        saveConfigBtn.addEventListener('click', async () => {
            const promptText = document.getElementById('promptConfig').value;
            if (!promptText) {
                alert('请输入提示词配置');
                return;
            }
            
            try {
                const response = await fetch('/api/save-prompt', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify({ prompt_text: promptText })
                });
                
                if (response.ok) {
                    alert('配置保存成功');
                    configDialog.style.display = 'none';
                } else {
                    throw new Error('保存失败');
                }
            } catch (error) {
                console.error('保存配置出错:', error);
                alert('保存配置出错: ' + error.message);
            }
        });
    </script>
</body>
</html>